<template>
  <el-card>
    <template #header>常用时段饼状图</template>
    <div :id="id" :class="className" :style="{ height, width }"></div>
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { onMounted, ref } from 'vue';
import { markRaw } from 'vue';
import { onActivated } from 'vue';
import axios from 'axios';

axios.defaults.baseURL = 'http://127.0.0.1:8080';

const props = defineProps({
  id: {
    type: String,
    default: "pieChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

const options = {
  grid: {
    left: "2%",
    right: "2%",
    bottom: "10%",
    containLabel: true,
  },
  legend: {
    top: "bottom",
    textStyle: {
      color: "#999",
    },
  },
  series: [
    
    { 
      name: "登录时段占比",
      type: "pie",
      radius: [50, 130],
      center: ["50%", "50%"],
      roseType: "area",
      itemStyle: {
        borderRadius: 1,
        color: function (params: any) {
          const colorList = ["#409EFF", "#67C23A", "#E6A23C", "#F56C6C"];
          return colorList[params.dataIndex];
        },
      },
      // data: [
      //   { value: 20, name: "0:00 - 6:00" },
      //   { value: 30, name: "6:00 - 12:00" },
      //   { value: 25, name: "12:00 - 18:00" },
      //   { value: 30, name: "18:00 - 24:00" },
      // ],
      data: [],
    },
  ],
};

const chart = ref<any>("");

onMounted(async () => {
  chart.value = markRaw(
    echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );

  console.log("Chart initialized.");

  await updateChartData(); // 调用updateChartData函数

  window.addEventListener("resize", () => {
    chart.value.resize();
  });
});

onActivated(() => {
  if (chart.value) {
    chart.value.resize();
  }
});

async function updateChartData() {
  try {
    console.log("Fetching chart data...");
    const response = await axios.get('/back/record/getBarChart2');
    console.log("Data fetched successfully.");
    const values = response.data; // 假设后端返回的数据格式是 [3, 0, 0, 0]

    if (values && values.length === 4) {
      // 创建一个新的数组，将每个值映射到对应的时间段
      const data = values.map((value, index) => {
        const timeRanges = [
          "0:00 - 6:00",
          "6:00 - 12:00",
          "12:00 - 18:00",
          "18:00 - 24:00"
        ];
        return { value, name: timeRanges[index] };
      });

      // 使用新创建的数据更新图表
      options.series[0].data = data;
      chart.value.setOption(options);
      console.log("Chart data updated successfully.");
    } else {
      console.error("Invalid data format from backend.");
    }
  } catch (error) {
    console.error("Error fetching chart data:", error);
  }
}


</script>
